package com.bydq.patrolsystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bydq.patrolsystem.entity.PsRolePremission;
import com.bydq.patrolsystem.entity.PsUser;
import com.bydq.patrolsystem.mapper.PsFunctionMapper;
import com.bydq.patrolsystem.mapper.PsRolePremissionMapper;
import com.bydq.patrolsystem.service.PsRolePremissionService;
import com.bydq.patrolsystem.vo.FunctionTreeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 写代码是不可能写代码的啦~~
 * @since 2020-05-22
 */
@Service
public class PsRolePremissionServiceImpl extends ServiceImpl<PsRolePremissionMapper, PsRolePremission> implements PsRolePremissionService {

    @Autowired
    private PsRolePremissionMapper psRolePremissionMapper;

    @Autowired
    private HttpSession session;

    @Autowired
    private PsFunctionMapper psFunctionMapper;

    @Override
    public Object[] listFunctionIdsByRoleId(Long id) {
        //根据角色id来查询当前权限功能的id
        Long[] ids = psRolePremissionMapper.selectFunctionIdsByRoleId(id);
        return ids;
    }


    /**
     * 根据角色id 设置权限
     * @param roleId
     * @param functionTreeVo
     * @return
     */
    @Override
    @Transactional
    public boolean setRoleAndPremission(Long roleId, List<FunctionTreeVo> functionTreeVo) {
        //获取session中的用户
        PsUser user = (PsUser) session.getAttribute("user");

        //遍历functionTreeVo树 获得function Id数组
        List<Long> longs = eachFunctionTreeVo(functionTreeVo, new ArrayList<Long>());

        Long[] integers = psRolePremissionMapper.selectFunctionIdsByRoleId(roleId);

        //遍历fucntionId开始添加
        for (Long aLong : longs) {

            //如果已经存在了这个关联就不用添加
            Integer count = psRolePremissionMapper.selectCount(new QueryWrapper<PsRolePremission>()
                    .eq("roleId", roleId)
                    .eq("functionCode", psFunctionMapper.getFunctionCodeByid(aLong))
            );

            if(count<1) {
                //添加
                psRolePremissionMapper.insert(new PsRolePremission(roleId,
                        //获取当前id对应的functionCode
                        psFunctionMapper.getFunctionCodeByid(aLong),
                        user.getUserCode()
                ));
            }
        }

        return true;
    }

    private List<Long> eachFunctionTreeVo(List<FunctionTreeVo> functionTreeVo, ArrayList<Long> strings) {
        if(functionTreeVo!=null) {
            for (FunctionTreeVo treeVo : functionTreeVo) {
                strings.add(treeVo.getId());
                eachFunctionTreeVo(treeVo.getChildren(),strings);
            }
        }
        return strings;
    }
}
